package net.tycmc.bulb.note.core.consumer.fltnote;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import net.tycmc.bulb.common.util.DateUtil;
import net.tycmc.bulb.common.util.StringUtil;
import net.tycmc.bulb.note.core.Util.JsonToMap;
import net.tycmc.bulb.note.core.handler.MQConnectionFactory;
import net.tycmc.bulb.note.core.handler.MQenum;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.ShutdownSignalException;
import com.tycmc.functions.util.DynamicReadConfig;
import com.tycmc.functions.util.MapGetter;


public class AccountBehaviorAnalysisConsumer{
	Logger log = Logger.getLogger("AccountBehaviorAnalysisConsumer");
	@Autowired
	private MQConnectionFactory connFactory;
	public static StringBuffer sbes=new StringBuffer();
	
	/**
	 * 定义用户行为分析的具体方法
	 * @throws FileNotFoundException 
	 * @throws ConfigurationException 
	 **/
	public void accountBehaviorAnalisis() throws FileNotFoundException, ConfigurationException{
		JsonToMap jtUtil = new JsonToMap();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//ExecutorService	executorService = Executors.newFixedThreadPool(1);
		//文件路径
		String path = DynamicReadConfig.getConfigProperty("config.properties", "Url");
		String DateTime=DateUtil.addDay(0);//程序启动的时候，当天的日期
		String finallyPath=path+DateTime+".txt";
		BufferedOutputStream fos=new BufferedOutputStream(new FileOutputStream(new File(finallyPath),true));
		String resultString="";
		try {
			Connection connection = connFactory.getConnection();
			Channel channel = connection.createChannel();
			channel.exchangeDeclare(MQenum.accountBehaviorExchange.getEnumValue(), MQenum.mqExchangeType.getEnumValue(), true);
			channel.queueDeclare(MQenum.accountBehaviorQueue.getEnumValue(), true, false, false, null);
			channel.queueBind(MQenum.accountBehaviorQueue.getEnumValue(), MQenum.accountBehaviorExchange.getEnumValue(), MQenum.accountBehaviorRouteKey.getEnumValue());
			QueueingConsumer consumer = new QueueingConsumer(channel);
			channel.basicConsume(MQenum.accountBehaviorQueue.getEnumValue(), false,consumer);
			String message = null;
			StringBuffer str = new StringBuffer();
			while(true){
				QueueingConsumer.Delivery delivery = consumer.nextDelivery();
				message = new String(delivery.getBody(),"UTF-8");				
				str.append(sdf.format(new Date())+":"+message+" \r\n");
				Map<String,Object> oneAlarm = jtUtil.jsonToMapSingle(message);
				if(null!=oneAlarm&&!oneAlarm.isEmpty()){
					String msgTime=MapGetter.getString(oneAlarm, "msgTime")+"@@";
					String browserName=MapGetter.getString(oneAlarm, "browserName")+"@@";
					String OS=MapGetter.getString(oneAlarm, "OS")+"@@";
					String ModelOperate=MapGetter.getString(oneAlarm, "ModelOperate")+"@@";
					String Account=MapGetter.getString(oneAlarm, "Account")+"@@";
					String UserName=MapGetter.getString(oneAlarm, "UserName")+"@@";
					String accountType=MapGetter.getString(oneAlarm, "accountType")+"@@";
					String UserIp=MapGetter.getString(oneAlarm, "UserIp")+"@@";
					String IpAddr=MapGetter.getString(oneAlarm, "IpAddr")+"@@";
					String searchParamString=MapGetter.getString(oneAlarm, "searchParamString");
					
					resultString="\r\n"+msgTime+browserName+OS+ModelOperate+Account+UserName+accountType+UserIp+IpAddr+searchParamString;
					/*String msgTime=MapGetter.getString(oneAlarm, "msgTime");
					String browserName=MapGetter.getString(oneAlarm, "browserName");
					String OS=MapGetter.getString(oneAlarm, "OS");
					String ModelOperate=MapGetter.getString(oneAlarm, "ModelOperate");
					String Account=MapGetter.getString(oneAlarm, "Account");
					String UserName=MapGetter.getString(oneAlarm, "UserName");
					String accountType=MapGetter.getString(oneAlarm, "accountType");
					String UserIp=MapGetter.getString(oneAlarm, "UserIp");
					String searchParamString=MapGetter.getString(oneAlarm, "searchParamString");
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("msgTime",msgTime);
					param.put("browserName",browserName);
					param.put("OS",OS);
					param.put("ModelOperate", ModelOperate);
					param.put("Account",Account);
					param.put("UserName",UserName);
					param.put("accountType",accountType);
					param.put("UserIp",UserIp);
					param.put("searchParamString",searchParamString);*/
					if(StringUtil.isValid(msgTime)&&msgTime.length()>10){
						String compareDate=msgTime.substring(0,10);
						if(!DateTime.equals(compareDate)){//时间相同，不用开启流
							//关闭流
							fos.flush();
							fos.close();
							DateTime=compareDate;
							finallyPath=path+compareDate+".txt";
							fos=new BufferedOutputStream(new FileOutputStream(new File(finallyPath),true)) ;
						}
					}
					fos.write(resultString.getBytes());
					fos.flush();
					//将用户行为分析数据封装为线程
					//executorService.submit(new AccountbaRunner(param));
				}else{
					log.info("accountBehaviorAnalisis"+sdf.format(new Date())+"接收到不能解析的消息——"+message);
				}
				channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
			}
		} catch (ShutdownSignalException e) {
			e.printStackTrace();
		} catch (ConsumerCancelledException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}			
  }
	public static void main(String[] args) throws IOException {
		FileOutputStream fos=new FileOutputStream("D://aabbcc.txt",false);
		fos.write("\n".getBytes());
		fos.write("aasdfsafsdaf".getBytes());
		fos.write("\r\n".getBytes());
		fos.write("aasdfsafsdaf".getBytes());
	}
}	


